#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

int main(){
    key_t key = ftok("/tmp",'A');
    if(key == EOF){
        perror("ftok");
        return 1;
    }

    printf("ftok generate key is %d\n", key);
    printf("ftok generate key is %x\n", key);

    int shmd = shmget(key, 1024,IPC_CREAT|0666);
    if(shmd == EOF){
        perror("shmget");
        return 1;
    }

    printf("shmget return shm id is %d\n",shmd);
    
    char* addr = shmat(shmd, NULL, 0);
    if(addr == NULL || addr == (void*)-1){
        perror("shmat");
        return 1;
    }

    printf("shmat return addr is %p\n",addr);
    do{
        fgets(addr, 20, stdin);
        if(strncmp(addr, "quit",4) == 0){
            break;
        }
    }while(1);
    
    printf("writer exit!\n");
    //卸载共享内存映射
    shmdt(addr);
    //删除共享内存
    shmctl(shmd, IPC_RMID, NULL);
    return 0;
}
